package org.aplikator.client.shared.rpc.marshaller;

import org.aplikator.client.shared.data.ContainerNode;
import org.aplikator.client.shared.data.RecordContainer;
import org.jboss.errai.marshalling.client.api.MarshallingSession;
import org.jboss.errai.marshalling.client.api.annotations.ClientMarshaller;
import org.jboss.errai.marshalling.client.api.annotations.ServerMarshaller;
import org.jboss.errai.marshalling.client.api.json.EJObject;
import org.jboss.errai.marshalling.client.api.json.EJValue;
import org.jboss.errai.marshalling.client.marshallers.AbstractNullableMarshaller;

import java.util.ArrayList;
import java.util.List;

@ClientMarshaller(RecordContainer.class)
@ServerMarshaller(RecordContainer.class)
@SuppressWarnings("unchecked")
public class RecordContainerMarshaller  extends AbstractNullableMarshaller<RecordContainer> {

	/*@Override
	public Class<RecordContainer> getTypeHandled() {
		return RecordContainer.class;
	}*/

	@Override
	public RecordContainer[] getEmptyArray() {
		return new RecordContainer[0];
	}

	@Override
	public RecordContainer doNotNullDemarshall(EJValue o, MarshallingSession ctx) {
		if (o.isObject() != null) {
			EJObject ejObject = o.isObject();
			List<ContainerNode> cnodes = new ArrayList<ContainerNode>();
			if (DemarshallingUtils.containsAndNotNull(ejObject, "nodes")) {
				cnodes = DemarshallingUtils.listUnMarshall(ejObject.get("nodes"), ctx, ContainerNode.class.getName());
			}
			RecordContainer container = new RecordContainer();
			container.setContainerNodes(cnodes);
			return container;
		} else  return null; 
	}

	@Override
	public String doNotNullMarshall(RecordContainer o, MarshallingSession ctx) {
		StringBuilder builder = new StringBuilder().append('{');
		MarshallingUtils.key("nodes", builder).append(':');
		MarshallingUtils.listMarshall(builder, o.getRecords(), ctx, ContainerNode.class.getName());
		builder.append('}');
		return builder.toString();
	}
}
